import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import { useUserStore } from '../stores/user'

const routes: RouteRecordRaw[] = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: { public: true, title: '登录' }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/Register.vue'),
    meta: { public: true, title: '注册' }
  },
  {
    path: '/',
    component: () => import('@/layouts/MainLayout.vue'),
    children: [
      {
        path: '',
        name: 'Dashboard',
        component: () => import('@/views/Dashboard.vue'),
        meta: { requiresAuth: true, title: '仪表盘' }
      },
      {
        path: 'profile',
        name: 'Profile',
        component: () => import('@/views/Profile.vue'),
        meta: { requiresAuth: true, title: '个人中心' }
      },
      {
        path: 'change-password',
        name: 'ChangePassword',
        component: () => import('@/views/ChangePassword.vue'),
        meta: { requiresAuth: true, title: '修改密码' }
      },
      {
        path: 'users',
        name: 'Users',
        component: () => import('@/views/Users.vue'),
        meta: { requiresAuth: true, title: '用户管理', roles: ['admin'] }
      },
      {
        path: 'articles',
        name: 'Articles',
        component: () => import('@/views/Articles.vue'),
        meta: { requiresAuth: true, title: '文章管理' }
      },
      {
        path: 'articles/detail/:id',
        name: 'ArticleDetail',
        component: () => import('@/views/ArticleDetail.vue'),
        meta: { requiresAuth: true, title: '文章详情' }
      },
      {
        path: 'articles/:id',
        name: 'ArticleEdit',
        component: () => import('@/views/ArticleForm.vue'),
        meta: { requiresAuth: true, title: '编辑文章', roles: ['admin','editor'] }
      }
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: {
      template: '<div style="padding:24px">页面未找到</div>'
    }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

router.beforeEach((to) => {
  const store = useUserStore()
  if (to.meta.public) return true
  if (to.meta.requiresAuth !== false && !store.token) {
    return { name: 'Login', query: { redirect: to.fullPath } }
  }
  const roles = (to.meta as any)?.roles as string[] | undefined
  if (roles && store.role && !roles.includes(store.role)) {
    return { name: 'Dashboard' }
  }
  return true
})

export default router


